const co = require('co');
const crypto = require('crypto');
const moment = require('moment');
const logger = require('../utils/logger');
const config = require('../config/config.json');

const payAddress = process.env.NBH_PAY_ADDRESS;
const merchantID = process.env.NBH_PAY_MERCHANT_ID;
const merchantKey = process.env.NBH_PAY_MERCHANT_KEY;

function sign(params) {
    let keys = Object.keys(params).sort();
    let sortedParams = {};
    for (k of keys) {
        sortedParams[k] = params[k];
    }
    let jsonString = JSON.stringify(sortedParams).toLowerCase();
    logger.info(`Sign json: ${jsonString}`);
    return crypto.createHash('md5').update(jsonString + merchantKey).digest('hex').toUpperCase();
}

let nbhPay = co.wrap(function *(billno, amount, notifyUrl, clientIp='127.0.0.1') {
    let params = {
        userNo: merchantID,
        accessNo: billno,
        accessTime: moment().format('YYYYMMDDHHmmss'),
        orderAmount: `${amount * 100}`,
        orderName: 'Account Creation',
        clientIp: clientIp,
        callBackUrl: notifyUrl,
        backUrl: config[process.env.NODE_ENV].serviceUrl
    };
    params.secretKey = sign(params);

    let url = payAddress + `/gateway/pay/choose?accessNo=${billno}&accessTime=${params.accessTime}`;

    return {
        openUrl: url,
        fields: params
    };
});

module.exports = {
    sign,
    nbhPay
};